package com.cf.service.impl;

import com.cf.dao.UserItemDao;
import com.cf.entity.Item;
import com.cf.service.UserItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@Transactional
@Service
public class UserItemServiceImpl implements UserItemService {
    @Autowired
    private UserItemDao userItemDao;
    @Override
    public PageInfo<Item> selectItemByUserId(int pagenum, int pagesize,long userid) {
        PageHelper.startPage(pagenum,pagesize);
        List<Item> items = userItemDao.selectItemByUserId(userid);
        for (Item item : items) {
            double  percentage =  item.getNmoney()/item.getAmoney()*100;
            long round = Math.round(percentage);
            item.setPercentage(round);
            //计算天数
            try {
                if (item.getIstart()==null||item.getIend()==null){
                    item.setDaybetween(0);
                }else {
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                    Date stime =sdf.parse(sdf.format(item.getIstart()));
                    Date etime =sdf.parse(sdf.format(item.getIend()));
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(stime);
                    long time1 = cal.getTimeInMillis();
                    cal.setTime(etime);
                    long time2 = cal.getTimeInMillis();
                    long between_days=(time2-time1)/(1000*3600*24);
                    item.setDaybetween(between_days);
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        PageInfo<Item> pageInfo =new PageInfo<>(items);
        return pageInfo;
    }

    @Override
    public int addUserItem(long userid, long iid) {
        return userItemDao.addUserItem(userid,iid);
    }
}
